#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
PDF合并工具启动脚本
自动检测环境并启动合适的版本
"""

import os
import sys
import subprocess
import importlib.util
import platform
import tkinter as tk
from tkinter import messagebox

def check_dependency(module_name):
    """
    检查是否安装了指定的模块
    """
    return importlib.util.find_spec(module_name) is not None

def install_dependency(module_name):
    """
    安装指定的模块
    """
    print(f"正在安装 {module_name}...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", module_name])
        return True
    except Exception as e:
        print(f"安装 {module_name} 失败: {str(e)}")
        return False

def main():
    """
    主函数
    """
    # 检查是否已安装PyPDF2
    if not check_dependency("PyPDF2"):
        # 如果未安装，尝试安装
        if not install_dependency("PyPDF2"):
            # 安装失败，显示错误消息
            root = tk.Tk()
            root.withdraw()
            messagebox.showerror(
                "错误", 
                "无法安装所需的依赖项 PyPDF2。\n\n"
                "请手动安装：\n"
                "1. 打开命令提示符或终端\n"
                "2. 输入命令：pip install PyPDF2\n"
                "3. 安装完成后重新运行此程序"
            )
            return
    
    # 确定当前脚本所在目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 检查是否存在增强版脚本
    enhanced_path = os.path.join(script_dir, "merge_pdfs_enhanced.py")
    basic_path = os.path.join(script_dir, "merge_pdfs.py")
    
    if os.path.exists(enhanced_path):
        # 运行增强版
        print("正在启动增强版PDF合并工具...")
        try:
            if platform.system() == "Windows":
                # 在Windows上使用pythonw.exe运行GUI程序（不显示控制台窗口）
                pythonw_path = os.path.join(os.path.dirname(sys.executable), "pythonw.exe")
                if os.path.exists(pythonw_path):
                    subprocess.Popen([pythonw_path, enhanced_path])
                else:
                    subprocess.Popen([sys.executable, enhanced_path])
            else:
                # 在其他平台上使用python运行
                subprocess.Popen([sys.executable, enhanced_path])
        except Exception as e:
            root = tk.Tk()
            root.withdraw()
            messagebox.showerror("错误", f"启动增强版工具失败: {str(e)}")
    elif os.path.exists(basic_path):
        # 运行基础版
        print("正在启动基础版PDF合并工具...")
        try:
            if platform.system() == "Windows":
                # 在Windows上使用pythonw.exe运行GUI程序（不显示控制台窗口）
                pythonw_path = os.path.join(os.path.dirname(sys.executable), "pythonw.exe")
                if os.path.exists(pythonw_path):
                    subprocess.Popen([pythonw_path, basic_path])
                else:
                    subprocess.Popen([sys.executable, basic_path])
            else:
                # 在其他平台上使用python运行
                subprocess.Popen([sys.executable, basic_path])
        except Exception as e:
            root = tk.Tk()
            root.withdraw()
            messagebox.showerror("错误", f"启动基础版工具失败: {str(e)}")
    else:
        # 未找到合并工具脚本
        root = tk.Tk()
        root.withdraw()
        messagebox.showerror("错误", "未找到PDF合并工具脚本文件。请确保merge_pdfs.py或merge_pdfs_enhanced.py在当前目录中。")

if __name__ == "__main__":
    main() 